% To calculate Coefficient of Variation for each Pij of std transition prob
% The mean was chosen by the average std probability instead of
% mathematical mean

clear all;
clc;
disp('To calculate Coefficient of Variation for each Pij of std transition prob');
load Prob_std_TP06YRJfinR5G1000kMR7.mat
load Avg_Prob_std_TP06YRJfinR5G1000kMR7.mat
% freqj=4;% 4 quarters
year_list=[1997:2009]';
year_list_text=num2str(year_list);
% quarter_list=[1:4]';
% quarter_list_text=num2str(quarter_list);
Rate_list=[0,1:0.5:5];
sigma=zeros(7,8);
CV=zeros(7,8);
X=zeros(7,8);

%prob=zeros(13,10,12);% the last column will be 1, so we ignore the 13th column and set it as 12 columns
%prob_std=zeros(13,10,12); % the 12th column is useless, we define 12 column for coding conveinence.
filename='TP06_Y_RJ_fin_R5_G1000k_MR7_CoefVar_avgstdprob.xls';
% filename2='TP06_Y_RJ_fin_R5_G1000k_MR7_transition prob_std.xls';

E=zeros(12,7,8); % take the needed data from prob_std. totaly 12yrs from 1998-2009. 7 ratings and 8 columns including default
E(:,:,1:7)=prob_std(2:13,3:9,3:9);
E(:,:,8)=prob_std(2:13,3:9,11);

miu(:,1:7)=stdprob(1,2:8,2:8);
miu(:,8)=stdprob(1,2:8,10);


for i=1:12
    Z(:,:)=E(i,:,:);
    X(:,:)= X(:,:) +((Z(:,:)-miu).^2); %.^2 is to square elements of matrix.
%     clear Z
end

sigma(:,:)=(X./12).^(0.5);
CV(:,:)=sigma(:,:)./abs(miu(:,:));
sheetlist=strcat('1998-2009_avgstdprob');
xlswrite(filename, CV, sheetlist);